<?php
/**
 * Controller 基类action
 */

namespace backend\controllers;

use common\utils\XString;
use yii;
use yii\data\ActiveDataProvider;

class CommonController extends BaseController
{
    /* @var $model yii\db\ActiveRecord */
    private $model;
    /* @var $query yii\db\Query */
    private $query;
    /* @var $view string */
    private $view;
    /* @var $params array */
    private $params = [];
    /* @var $url string|array */
    private $url;
    /* @var $url Yii::$app->request */
    protected $request;
    /* @var $pageSize int */
    protected $pageSize = 20;

    public function init()
    {
        parent::init();
        $this->request = Yii::$app->request;
    }

    /**
     * 返回列表页
     * 调用前需要设置$query
     * @return string
     */
    protected function query()
    {
        if ($this->pageSize === 0) {
            $dataProvider = new ActiveDataProvider([
                'query' => $this->query,
                'pagination' => false
            ]);
        } else {
            $dataProvider = new ActiveDataProvider([
                'query' => $this->query,
                'pagination' => [
                    'pageSize' => $this->pageSize,
                ]
            ]);
        }
        if (!$this->view) {
            $this->view = 'index';
        }
        return $this->render($this->view, array_merge(['dataProvider' => $dataProvider], $this->params));
    }

    /**
     * 保存
     * 调用前需要设置$model
     * @return string
     */
    protected function save()
    {
        if ($this->model->load(Yii::$app->request->post()) && $this->model->validate()) {
            $this->modelHandle($this->model);
            if ($this->model->save()) {
                $this->savedHandle($this->model);
                if (!$this->url) {
                    $this->url = ['index'];
                }
                $this->redirect($this->url, 301);
            } else {
                $this->tips("保存失败！");
            }
        }
        if (!$this->view) {
            $this->view = 'form';
        }
        return $this->render($this->view, array_merge(['model' => $this->model], $this->params));
    }

    /**
     * 删除
     * 调用前需要设置$model
     * @throws \Exception
     */
    protected function delete()
    {
        $id = Yii::$app->request->get('id');
        if ($id == null) {
            $id = Yii::$app->request->post('id');
        }
        if (is_array($id)) {
            $id = implode(',', $id);
        }
        if ($id) {
            $modelList = $this->model->find()->where('id in(:id)', [':id' => $id])->all();
            if ($modelList) {
                foreach ($modelList as $model) {
                    $model->delete();
                }
                if (!$this->url) {
                    $this->url = ['index', 'page' => Yii::$app->request->get('page')];
                }
                $this->deletedHandle($id);
                $this->redirect($this->url, 301);
            } else {
                $this->tips("要删除的记录已经不存在！");
            }
        } else {
            $this->tips("删除的参数不对！");
        }
    }

    /**
     * 设置$model
     * @param $model yii\db\ActiveRecord
     */
    protected function setModel($model)
    {
        $this->model = $model;
    }

    /**
     * 设置$query
     * @param $query yii\db\Query
     */
    protected function setQuery($query)
    {
        $this->query = $query;
    }

    /**
     * 设置页面的$view
     * @param $view string
     */
    protected function setXView($view)
    {
        $this->view = $view;
    }

    /**
     * 保存前对$model的处理
     * @param $model yii\db\ActiveRecord
     */
    protected function modelHandle($model)
    {

    }

    /**
     * 保存后对$model的处理
     * @param $model yii\db\ActiveRecord
     */
    protected function savedHandle($model)
    {

    }

    /**
     * 删除后的处理
     * @param $id
     */
    protected function deletedHandle($id)
    {

    }

    /**
     * 渲染$view的赋值
     * @param $params array
     */
    protected function setParams($params)
    {
        $this->params = $params;
    }

    /**
     * 设置跳转的地址
     * @param $url array
     */
    protected function setUrl($url)
    {
        $this->url = $url;
    }

    /**
     * 获取$_GET参数
     * @param $name string
     * @return array|mixed
     */
    protected function get($name)
    {
        return Yii::$app->request->get($name);
    }

    /**
     * 获取$_POST参数
     * @param $name string
     * @return array|mixed
     */
    protected function post($name)
    {
        return Yii::$app->request->post($name);
    }

    /**
     * 设置分布大小
     * @param $pageSize
     */
    protected function setPageSize($pageSize)
    {
        $this->pageSize = $pageSize;
    }

    /**
     * 通过\kartik\file\FileInput上传组图
     * @return array
     */
    public function actionUploadPhotos()
    {
        Yii::$app->response->format = yii\web\Response::FORMAT_JSON;
        if ($this->post('key')) {
            @unlink(Yii::getAlias('@frontend') . '/web' . $this->post('key'));
            return ['success' => true];
        } else {
            $modelName = $this->get('modelName');
            // $p1 $p2是我们处理完图片之后需要返回的信息
            $p1 = $p2 = [];
            if (empty($_FILES[$modelName]['name']) || empty($_FILES[$modelName]['name']['photos'])) {
                return [];
            }

            $files = yii\web\UploadedFile::getInstancesByName($modelName . '[photos]');
            if (!$files) {
                return [];
            }
            $path = Yii::getAlias('@frontend') . '/web';
            $_path = '/uploads/image/' . date('Ymd');
            if (!file_exists($path . $_path)) {
                mkdir($path . $_path);
            }
            foreach ($files as $file) {
                $imageUrl = $_path . '/' . time() . XString::ranStr() . '.' . $file->getExtension();
                $file->saveAs($path . $imageUrl);
                //$p1[] = yii\helpers\Html::img(Yii::getAlias('@frontendUrl') . $imageUrl, ['width' => 180, 'height' => 180]);
                $p1[] = Yii::getAlias('@frontendUrl') . $imageUrl;
                $p2[] = ['url' => yii\helpers\Url::to(['upload-photos']), 'key' => $imageUrl];
            }

            // 返回上传成功后的图片信息
            return [
                'initialPreview' => $p1,
                'initialPreviewConfig' => $p2,
                'append' => true,
            ];
        }
    }
}